package gitobject;

import sha1.SHA1;
import zlib.ZLibUtils;

import java.io.*;

public class Blob extends GitObject{
    
	public String getFmt(){
        return fmt;
    }
    public String getMode(){
        return mode;
    }
    public String getPath() {
        return path;
    }
    public String getValue(){
        return value;
    }
    public String getKey() { return key; }
    public Blob(){};
    /**
     * Constructing blob object from a file
     * @param file
     * @throws Exception
     */
    public Blob(File file) throws Exception {
        fmt = "blob";
        mode = "100644";
        //value & genKey的file参数都来自于工作区
        value = getValue(file);
        genKey(file);
        //writeObject();
    }

    /**
     * Deserialize a blob object from an existed hash file in .jit/objects.
     * @param Id
     */
    public static Blob deserialize(String Id) {
        String absPath = path + File.separator + Id.substring(0,2) + File.separator + Id.substring(2);
        Blob b = new Blob();
        try{
            FileInputStream is = new FileInputStream(absPath);
            ObjectInputStream os = new ObjectInputStream(is);
            b = (Blob)os.readObject();
            os.close();
            is.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return b;
    }

    /**
     * Generate key from file.
     * @param file
     * @return String
     * @throws Exception
     */
    public String genKey(File file) throws Exception {

        this.key = SHA1.getHash(file);
        return key;
    }

    @Override
    public String toString(){
        return "100644 blob " + key;
    }
}
